home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 9847 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.2 KB

  1. Path: mail2news.demon.co.uk!genesis.demon.co.uk
  2. From: Lawrence Kirby <fred@genesis.demon.co.uk>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: while loop problem
  5. Date: Wed, 13 Mar 96 18:06:16 GMT
  6. Organization: none
  7. Distribution: world
  8. Message-ID: <826740376snz@genesis.demon.co.uk>
  9. References: <Pine.OSF.3.91.960312133449.7844B-100000@io.UWinnipeg.ca> <Pine.A32.3.91.960312145524.69354D-100000@red.weeg.uiowa.edu>
  10. Reply-To: fred@genesis.demon.co.uk
  11. X-NNTP-Posting-Host: genesis.demon.co.uk
  12. X-Newsreader: Demon Internet Simple News v1.27
  13. X-Mail2News-Path: genesis.demon.co.uk
  14.  
  15. In article <Pine.A32.3.91.960312145524.69354D-100000@red.weeg.uiowa.edu>
  16.            robinson@blue.weeg.uiowa.edu "The Amorphous Mass" writes:
  17.  
  18. >On Tue, 12 Mar 1996, Bill Simpson wrote:
  19. >
  20. >> Consider the following code fragment:
  21. >> 
  22. >> y=2000; z=1000;
  23. >> x=0;
  24. >> while(x<=XMAX)
  25. >>       {
  26. >>       x+=(int) erand(mean);
  27. >>       setdot(x,y,z);
  28. >>       }
  29. >
  30. >  y = 2000; z = 1000; x = 0;
  31. >
  32. >  do {
  33. >     setdot(x,y,z);
  34. >     x += (int)erand(mean);
  35. >  } while (x <= XMAX);
  36.  
  37. Compared to the original this sets an extra dot at x==0. Others have
  38. 'improved' on this by writing something similar to:
  39.  
  40. >  y = 2000; z = 1000;
  41. >  x = (int)erand(mean);
  42. >
  43. >  do {
  44. >     setdot(x,y,z);
  45. >     x += (int)erand(mean);
  46. >  } while (x <= XMAX);
  47.  
  48. but this doesn't test the first value of x so is invalid unless you
  49. know that (int)erand(mean) <= XMAX is guaranteed is guaranteed (which isn't stated). That
  50. can be fixed by moving the test to the top i.e.
  51.  
  52.     y = 2000; z = 1000;
  53.     x = (int)erand(mean);
  54.  
  55.     while (x <= XMAX) {
  56.        setdot(x,y,z);
  57.        x += (int)erand(mean);
  58.     }
  59.  
  60. which can also be written as:
  61.  
  62.     y = 2000; z = 1000;
  63.     x = (int)erand(mean);
  64.  
  65.     for (x = (int)erand(mean); x <= XMAX; x += (int)erand(mean))
  66.         setdot(x,y,z);
  67.  
  68. Bill's 2nd article also contains a correct version. It can be written more
  69. compactly as:
  70.  
  71.     y = 2000; z = 1000;
  72.  
  73.     x = 0;
  74.     while ((x += (int)erand(mean)) <= XMAX)
  75.         setdot(x,y,z);
  76.  
  77. You could write this as a for loop but I prefer it in this form.
  78.  
  79. -- 
  80. -----------------------------------------
  81. Lawrence Kirby | fred@genesis.demon.co.uk
  82. Wilts, England | 70734.126@compuserve.com
  83. -----------------------------------------
  84.